use std::error::Error;
use serde::{Deserialize, Serialize};
use sqlx::Type;
use crate::ErrorCode::CodeRpcInternalError;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[sqlx(type_name = "TINYINT")]
pub enum BalanceType {
    #[sqlx(rename = "1")]
    Available=1,
    #[sqlx(rename = "2")]
    Margin=2,
    #[sqlx(rename = "3")]
    FrozenFee=3,
    #[sqlx(rename = "4")]
    FrozenMargin=4,
    #[sqlx(rename = "5")]
    ProfitUnreal=5,
}

impl BalanceType {
    pub fn code(&self) -> u8 {
        *self as u8
    }

    pub fn from_code(code: u8) -> Result<Self, Box<dyn Error>> {
        match code {
            1 => Ok(BalanceType::Available),
            2 => Ok(BalanceType::Margin),
            3 => Ok(BalanceType::FrozenFee),
            4 => Ok(BalanceType::FrozenMargin),
            5 => Ok(BalanceType::ProfitUnreal),
            _c => Err(CodeRpcInternalError.into()),
        }
    }
}